package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.OrderResult;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetmeal;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private AddressDao addressDao;
    /**
     * 在线体检预约
     *
     * @param map
     * @return
     * @throws Exception
     */



    //体检预约
    public Result order(Map map) throws Exception{

        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting= orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if(orderSetting == null){
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //获取可预约人数
        int number = orderSetting.getNumber();
        //获取已预约人数
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            //如果已预约人数大于等于可预约人数，说明不能在预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //获取手机号
        String telephone = (String) map.get("telephone");
        //通过手机号检查当前用户是否是会员
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            //获取预约体检人姓名
            String name = (String) map.get("name");
            //获取会员id
            Integer memberId = member.getId();
            //获取预约日期
            String setmealId = (String) map.get("setmealId");
            //将参数获取的参数封装成对象
            Order order = new Order(memberId, DateUtils.parseString2Date(orderDate), Integer.parseInt(setmealId),name);
            //通过对象进行查询
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //如果查询不为空，说明同一天预约了同一个套餐
                return new Result(false, MessageConstant.HAS_ORDERED);
            }

        } else {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setSex((String) map.get("sex"));
            member.setIdCard((String) map.get("idCard"));
            member.setPhoneNumber((String) map.get("telephone"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }



        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setName((String) map.get("name"));
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        orderDao.addorderList(order);
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderDao.add(order);

        //添加关联表t_order_address 绑定一个订单对应的地址
        Integer orderId = order.getId();//会员id
        Integer addressId = addressDao.findIdByAddress((String)map.get("addressDetails"));
        Map<String,Integer> map1 = new HashMap<>();
        map1.put("address_id",addressId);
        map1.put("order_id",orderId);
        addressDao.save(map1);

        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
     *
     * @param id
     * @return
     */

    @Override
    public Order getOrder(Integer orderId) {
        Order order=orderDao.getOrder(orderId);
        return order;
    }

    @Override
    public void updateState(Integer orderId) {
        orderDao.updateState(orderId);
    }

    @Override
    public String findStateById(Integer id) {
        String state=orderDao.findStateById(id);
        return state;
    }


    //根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
    public Map findById(Integer id) throws Exception{
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    @Override
    public Map<String, Object> findOrderAndSetmeal(OrderSetmeal orderSetmeal) {
        return orderDao.findOrderAndSetmeal(orderSetmeal);
    }


    /**
     * 预约订单管理分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage,pageSize);
        Map<String,Object> map = (Map) JSON.parse(queryPageBean.getQueryString());
        List<Order> list=orderDao.findListByCondition(map);
        PageInfo<Order> pageInfo=new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 预约订单管理页面编辑数据的回显
     * @param id
     * @return
     */
    @Override
    public Order findByOrderId(int id) {
        return orderDao.findByOrderId(id);

    }


    /**
     * 编辑预约信息
     * @param order
     */
    @Override
    public void editByOrderId(Order order) {
        orderDao.editByOrderId(order);
    }

    /**
     * 更改预约信息状态
     * @param order
     */
    @Override
    public void changeStatus(Order order) {
        orderDao.changeStatus(order);
    }

    /**
     * 删除预约信息
     * @param id
     */
    @Override
    public void deleteByorderId(int id) {
        //删除预约
        orderDao.deleteByorderId(id);
    }


    /**
     * 添加预约信息
     * @param map
     * @return
     */
    @Override
    public Result addOrder(Map<String, String> map)throws Exception {
        //获取预约日期
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = null;
        //通过预约日期查询预约设置
        orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //获取可预约人数
        int number = orderSetting.getNumber();
        //获取已预约人数
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            //如果已预约人数大于等于可预约人数，说明不能在预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //获取手机号
        String telephone = (String) map.get("telephone");
        //通过手机号检查当前用户是否是会员
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Integer memberId = member.getId();
            String setmealId = (String) map.get("setmealId");
            Order order = new Order(memberId, DateUtils.parseString2Date(orderDate), Integer.parseInt(setmealId));
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //如果查询不为空，说明同一天预约了同一个套餐
                return new Result(false, MessageConstant.HAS_ORDERED);
            }

        } else {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setSex((String) map.get("sex"));
            member.setIdCard((String) map.get("idCard"));
            member.setPhoneNumber((String) map.get("telephone"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        orderDao.addorderList(order);
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        //预约成功，直接返回预约id
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }



    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //使用分页插件进行分页
        PageHelper.startPage(currentPage,pageSize);
        //调用方法进行查询操作
        Page<OrderResult> orders = orderDao.selectByCondition(queryString);

        return new PageResult(orders.getTotal(),orders.getResult());
    }

    //通过电话号码获取到预约信息
    @Override
    public List<Order> findByMemberTelephone(String telephone) {
        //获取到member的id
        Member member = memberDao.findByTelephone(telephone);
        Integer id = member.getId();

        //获取到orderList集合
        List<Order> orderList = orderDao.findByMemberId(id);

        if (orderList != null && orderList.size() > 0 ){
            for (Order order : orderList) {
                Integer setmealId = order.getSetmealId();
                Setmeal setmeal = setmealDao.findById(setmealId);
                order.setSetmeal(setmeal);
                order.setMember(member);
            }
        }

        return orderList;
    }

    //修改预约状态
    @Override
    public void changeStatus(Integer id) {
        Order order = orderDao.findByOrderIdWGL(id);
        if ("未到诊".equals(order.getOrderStatus())){
            order.setOrderStatus("已到诊");
        }else {
            order.setOrderStatus("未到诊");
        }
        orderDao.changeStatus(order);
    }



}
